package org.example.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.VulnMapper;
import org.example.pojo.*;
import org.example.service.VulnService;
import org.example.utils.Loggable;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/vuln")
public class VulnController {
    @Autowired
    private VulnService vulnService;
    @Autowired
    private VulnMapper vulnMapper;
    private Map<Integer, Integer> taskProgress = new ConcurrentHashMap<>();

    @Loggable(action = "获取漏洞列表")
    @GetMapping()
    public Result vulnList(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer size,Integer tempId, Integer scanId,  String cveId, String vulnName, String vulnType, String severity,String status, String start, String end, String keywords) {
        PageBean pageBean = vulnService.vulnList(page, size,tempId, scanId, cveId, vulnName, vulnType, severity,status, start, end, keywords);
        return Result.success(pageBean);
    }

    @Loggable(action = "删除漏洞")
    @DeleteMapping()
    public Result deleteVuln(@RequestBody List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            Integer id = ids.get(i);
            Vulnerabilities vuln = vulnMapper.getVulnById(id);
            if (vuln.getTempId() != null) {
                return Result.error("无法删除用户导入的漏洞模板");
            }
        }
        vulnMapper.deleteVuln(ids);
        return Result.success();
    }
    @Loggable(action = "上传漏洞")
    @PostMapping("/add")
    public Result addvuln(@RequestBody Vulnerabilities vulnerabilities) {
        vulnMapper.insert(vulnerabilities);
        return Result.success();
    }

    @Loggable(action = "获取扫描任务列表")
    @GetMapping("/scan/task/list")
    public Result scanList(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer size, String taskName, String start, String end, String status) {
        PageBean pageBean = vulnService.scanList(page, size, taskName, start, end, status);
        return Result.success(pageBean);
    }

    @Loggable(action = "新建扫描任务")
    @PostMapping("/scan/task/add")
    public Result vulnScan(@RequestBody VulnScanTask vulnScanTask) {
        vulnMapper.addScanTask(vulnScanTask);
        return Result.success();
    }

    @Loggable(action = "删除扫描任务")
    @DeleteMapping("/scan/task")
    public Result delScanTasks(@RequestBody List<Integer> ids) {
        vulnMapper.delScanTasks(ids);
        return Result.success();
    }
    @Loggable(action = "修改扫描任务")
    @PutMapping("/scan/task")
    public Result updateScanTask(@RequestBody VulnScanTask vulnScanTask) {
        vulnMapper.updateScanTask(vulnScanTask);
        return Result.success();
    }

    @Loggable(action = "开启扫描任务")
    @PutMapping("/scan/start/{taskId}")
    public Result startScan(@PathVariable Integer taskId) {
//        VulnScanTask task = vulnMapper.getScanTaskById(taskId);
//        ScanHistoryVO scanHistoryVO = new ScanHistoryVO();
//        scanHistoryVO.setTaskId(taskId);
//        scanHistoryVO.setTaskName(task.getTaskName());
//        scanHistoryVO.setExcuteWay(task.getExcuteWay());
//        scanHistoryVO.setExcuteTime(task.getExcuteTime());
//        scanHistoryVO.setDayOfWeek(task.getDayOfWeek());
//        vulnMapper.startScan(scanHistoryVO);
        return vulnService.scanTaskScheduler(taskId);
    }
    @PutMapping("/scan/stop")
    public Result stopScan(@RequestBody ScanHistoryVO scanHistoryVO) {
        return vulnService.cancelScanTask(scanHistoryVO);
    }
    @Loggable(action = "获取扫描历史列表")
    @GetMapping("/scan/history/list")
    public Result getScanHisList(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer size, String taskName, String start, String end, String status) {
        PageHelper.startPage(page, size);
        List<ScanHistoryVO> scanHistoryList = vulnMapper.getScanHistoryList(taskName, start, end, status);
        scanHistoryList.forEach(item -> {
            Integer num = vulnMapper.getVulnNumByScanId(item.getId());
            item.setVulnNum(num);
        });
        Page<ScanHistoryVO> p = (Page<ScanHistoryVO>) scanHistoryList;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pageBean);
    }

    @Loggable(action = "删除扫描历史")
    @DeleteMapping("/scan/history")
    public Result delScanHistory(@RequestBody List<Integer> ids) {

        Integer id = ids.get(0);
        ScanHistoryVO history = vulnMapper.getScanHistoryById(id);
        if (!Objects.equals(history.getExcuteWay(), "单次")) {
            vulnService.cancelScanTask(history);
        }
        vulnMapper.delScanHistory(ids);
        return Result.success();
    }

    @GetMapping("/scan/progress/{historyVOId}")
    public Result getScanProgress(@PathVariable Integer historyVOId) {
        return Result.success(vulnService.scanProgress(historyVOId));
    }

    @Loggable(action = "获取漏洞模板列表")
    @GetMapping("/temp/list")
    public Result getVulnTempList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size) {
        PageHelper.startPage(page, size);
        List<VulnTempVO> vulnTempList = vulnMapper.getVulnTempList();
        Page<VulnTempVO> p = (Page<VulnTempVO>) vulnTempList;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pageBean);
    }
    @Loggable(action = "删除漏洞模板")
    @DeleteMapping("/temp/{id}")
    public Result delVulnTemp(@PathVariable Integer id) {
        vulnMapper.delVulnTemp(id);
        vulnMapper.delVulnByTempId(id);
        return Result.success();
    }
    @Loggable(action = "安全风险分析")
    @GetMapping("/risk/retend")
    public Result getSecurityTends() {
        List<VulnerabilityCount> countLast7Days = vulnService.getVulnerabilityCountLast7Days();
        return Result.success(countLast7Days);
    }

    @GetMapping("/eve/count")
    public Result getVulnEveCount() {
        VulnTypeCount vulnTypeCount = vulnMapper.countVulnByMonitor();
        return Result.success(vulnTypeCount);
    }
    @Loggable(action = "修改漏洞状态")
    @PutMapping("/status")
    public Result setVulnStatus(@RequestBody Map<String, Object> obj) {
        List<Integer> ids = (List<Integer>) obj.get("ids");
        String status = (String) obj.get("status");
        vulnMapper.setVulnStatus(ids, status);
        return Result.success();
    }
}
